<?php

// $Id$

require_once('../../boot.inc.php');
boot('my_site');

// discarding output buffering
ob_end_clean();

require_once(TANGRA_MAIN_DIR.'core/config_loader_file.class.php');

require_once($WSC->get_site_inc_dir().'modules/captcha/captcha.class.php');

session_start();


if (array_key_exists(Captcha::SESSION_VAR_NAME, $_SESSION)) {
	$config_loader = new Config_Loader_File($WSC->get_conf_dir().'modules/captcha/captcha.conf');
	$path_to_ttf = $WSC->get_root_dir().$config_loader->get_conf_value('PATH_TO_TTF_FONT');
	$height = $config_loader->get_conf_value('HEIGHT');
	$width = $config_loader->get_conf_value('WIDTH');
	$font_size = $config_loader->get_conf_value('FONT_SIZE');

	$code = $_SESSION[Captcha::SESSION_VAR_NAME];

	/* font size will be 75% of the image height */



	$image = imagecreate($width, $height) or die('Cannot initialize new GD image stream');

	/* set the colours */
	$tmp_color = captcha_generate_random_color(155, 255);
	$background_color = imagecolorallocate($image, $tmp_color['red'], $tmp_color['green'], $tmp_color['blue']);

	$tmp_color = captcha_generate_random_color(0, 127);
	$text_color = imagecolorallocate($image, $tmp_color['red'], $tmp_color['green'], $tmp_color['blue']);
	$noise_color1 = imagecolorallocate($image, $tmp_color['red'], $tmp_color['green'], $tmp_color['blue']);
	$noise_color2 = imagecolorallocate($image, $tmp_color['red'] + mt_rand(10, 40), $tmp_color['green'] + mt_rand(10, 40), $tmp_color['blue'] + mt_rand(10, 40));


	/* generate random dots in background */
	for( $i=0; $i < ($width * $height) / 3; $i++) {
	 imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color1);
	}


	/* generate random lines in background */
	for($i=0; $i < ($width * $height) / 250; $i++ ) {
	 imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color1);
	}
//	for($i=0; $i < ($width * $height) / 300; $i++ ) {
//	 imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color2);
//	}

	/* create textbox and add text */
	$textbox = imagettfbbox($font_size, 0, $path_to_ttf, $code) or die('Error in imagettfbbox function');
	$angle = mt_rand(5,18) * ((mt_rand(1,2) == 1) ? (-1) : 1);
	$x = ($width - $textbox[4])/2;

	if ($angle > 0) {
		$y = ($height - $textbox[5])/2 + $angle * 0.5;
	} else {
		$y = ($height - $textbox[5])/2 + $angle * 0.7;
	}


	imagettftext($image, $font_size, $angle, $x, $y, $text_color, $path_to_ttf , $code) or die('Error in imagettftext function');

	/* output captcha image to browser */
	header('Content-Type: image/jpeg');
	imagejpeg($image);
	imagedestroy($image);
} else {
	printbr('Your session has expired. Please try again.');
}


function captcha_generate_random_color($min, $max) {
	$ret['red'] = intval(mt_rand($min, $max));
	$ret['green'] = intval(mt_rand($min, $max));
	$ret['blue'] = intval(mt_rand($min, $max));

	return $ret;
}